<template>
  <div>
    <!-- 面包屑导航区 -->
    <bread-crumb :breadPath="breadPath"></bread-crumb>
    <!-- 卡片视图区 -->
    <el-card class="box-card">
      <!-- 提示信息 -->
      <el-alert title="添加商品信息" type="info" :closable="false" show-icon center></el-alert>
      <!-- 添加操作的步骤条 -->
      <el-steps :space="200" :active="stepActiveIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 添加表单 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
        <!-- 表单的 左侧标签页 -->
        <el-tabs :tab-position="'left'"  v-model="stepActiveIndex" :before-leave="beforeTabLeave" @tab-click="tabClicked">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader v-model="addForm.goods_cat" :options="cateList" 
                      :props="cascaderProps" @change="parentCateChanged" clearable>
              </el-cascader>
            </el-form-item>
            <el-form-item label="商品名称" prop="goods_name" style="width: 80%">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-row>
              <el-col :span="5">
                <el-form-item label="商品价格(元)" prop="goods_price">
                  <el-input v-model="addForm.goods_price" type="number"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5" :offset="2">
                <el-form-item label="商品数量" prop="goods_number">
                  <el-input v-model="addForm.goods_number" type="number"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="5" :offset="2">
                <el-form-item label="商品重量(千克)" prop="goods_weight">
                  <el-input v-model="addForm.goods_weight" type="number"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="(item, i) in manyAttrs" :key="item.attr_id">
              <el-checkbox-group v-model="addForm.many_attrs[i].attr_vals">
                <el-checkbox :label="checkItem" v-for="(checkItem, i) in item.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in addForm.only_attrs" :key="item.attr_id">
              <div class="inputDeep">
                <el-input v-model="item.attr_vals"></el-input>
              </div>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action表示图片要上传到的后台API地址 -->
            <el-upload :action="uploadURL" :on-preview="handlePreview" :on-success="handleSuccess"
                       :on-remove="handleRemove"  list-type="picture" :headers="headerObj">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本插件 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!-- 添加商品按钮 -->
            <el-button type="primary" @click="addGood" class="addButton">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览对话框 -->
    <el-dialog :visible.sync="imgDialogVisible" width="50%">
      <img :src="fileURL" alt="图片地址错误" class="previewImg">
    </el-dialog>
  </div>
</template>

<script>
  import breadCrumb from '@/components/breadcrumb'
  import { getCategories, getParamsById, postAddGood } from '@/api/goods.js';
  // 插件包 使用其中的深拷贝函数
  import _ from 'lodash'

  export default {
    data() {
      return {
        // 面包屑 传参
        breadPath: ['商品管理', this.$route.query.bread],
        // 步骤条 激活的步骤项
        stepActiveIndex: '0',
        // 添加表单绑定的数据对象
        addForm: {
          goods_name: '',
          // 级联选择器 当前选中的 分类id 因分有多级，所以类型是一个数组。
          goods_cat: [],
          goods_price: null,
          goods_number: null,
          goods_weight: null,
          // 上传图片的临时路径对象数组
          pics: [],
          // 商品对应分类下的  所属动态参数和静态属性
          many_attrs: [],
          only_attrs: [],
          // 商品介绍 富文本数据
          goods_introduce: ''
        },
        // 添加表单的验证规则
        addFormRules: {
          goods_name: [
            { required: true, message: '请输入商品名称', trigger: 'blur' },
          ],
          goods_price: [
            { required: true, message: '请输入商品价格', trigger: 'blur' },
          ],
          goods_number: [
            { required: true, message: '请输入商品数量', trigger: 'blur' },
          ],
          goods_weight: [
            { required: true, message: '请输入商品重量', trigger: 'blur' },
          ],
          goods_cat: [
            { required: true, message: '请选择商品分类', trigger: 'change' },
          ],
        },
        // 商品分类 级联选择器 选项数据
        cateList: [],
        // 商品分类对应的动态参数
        manyAttrs: [],
        // 级联选择器的数据对象 用于配置级联选择器选项的表现效果
        cascaderProps: {
          expandTrigger: 'hover',
          value: 'cat_id',
          label: 'cat_name',
          children: 'children'
        },
        // 上传图片的URL地址
        uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
        // 上传API配置请求头信息 加入token
        headerObj: { Authorization: window.sessionStorage.getItem('token')},
        // 上传图片的预览对话框对应图片的地址
        fileURL: '',
        // 图片对话框的 显示和隐藏
        imgDialogVisible: false
      }
    },
    created() {
      this.getCateList();
    },
    computed: {
      cateId() {
        if (this.addForm.goods_cat.length === 3) {
          return this.addForm.goods_cat[2];
        }
        return null;
      }
    },
    methods: {
      // 获取商品分类列表数据 for级联选择器
      async getCateList() {
        await getCategories()
          .then((res) => {
            this.cateList = res.data;
            // console.log(this.cateList);
          }).catch(err => err);
      },
      // 级联选择器 选项更改时 触发该函数
      parentCateChanged(value) {
        // 如果选择的不是第三级，则不会在selectedKeys中存储对应的分类ID
        if ( value.length != 3 && value.length != 0 ) {
          this.addForm.goods_cat = [];
          return this.$message.error('请选择三级分类');
        }
        this.addForm.goods_cat = value;
        // console.log(this.addForm);
      },
      // 切换标签页时 触发该函数 判断是否阻止切换
      beforeTabLeave(activeName, oldActiveName) {
        if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
          this.$message.error('请先选择商品分类');
          return false;
        }
      },
      // 深拷贝函数
      deepClone(obj) {
        var newobj = {};
        try {
          newobj = JSON.parse(JSON.stringify(obj));
        }
        catch(err){console.log(err);}
        return newobj;
      },
      // 点击标签页时触发
      async tabClicked() {
        // console.log(this.stepActiveIndex);
        if (this.stepActiveIndex === '1') {
          let { data: res } = await getParamsById(this.cateId, 'many').catch(err => err);
          res.forEach(element => {
            element.attr_vals = element.attr_vals.length === 0 ? [] : element.attr_vals.split(' ');
          });
          this.manyAttrs = res;
          // 深拷贝动态参数对象 将其attr_vals值保留第一个作为默认选项 赋值给addForm.many_attrs
          let cloneManyAttrs = this.deepClone(res);
          cloneManyAttrs.forEach(element => {
            let fristVal = element.attr_vals.shift();
            element.attr_vals = [fristVal];
          });
          this.addForm.many_attrs = cloneManyAttrs;
          console.log(this.manyAttrs);
          console.log(this.addForm.many_attrs);
        } else if (this.stepActiveIndex === '2') {
          const { data: res } = await getParamsById(this.cateId, 'only').catch(err => err);
          this.addForm.only_attrs = res ;
        }
      },
      // 上传图片 点击图片的预览事件
      handlePreview(file) {
        // 获取图片对应真实的地址 存入示例数据中
        this.fileURL = file.response.data.url;
        // 显示对话框
        this.imgDialogVisible = true;
      },
      // 上传图片 点击删除图片的事件
      handleRemove(file) {
        // console.log(file);
        // 保存要删除的图片对应path
        const filePath = file.response.data.tmp_path;
        // 查找path对应的数组id 根据id删除
        const picIndex = this.addForm.pics.findIndex(x => x.pic === filePath);
        this.addForm.pics.splice(picIndex,1);
        console.log(this.addForm.pics);
      },
      // 上传图片成功后 触发的钩子函数
      handleSuccess(response) {
        // 构建一个对象 图片信息对象
        const picInfo = { "pic": response.data.tmp_path };
        // push该对象到addform.pics数组中
        this.addForm.pics.push(picInfo);
        console.log(this.addForm);
      },
      // 添加商品按钮 触发添加商品请求
      addGood() {
        // console.log(this.addForm.goods_introduce);
        // 验证表单必填项是否填有数据
        this.$refs.addFormRef.validate((valid) => {
          if (!valid) {
            // 信息不全，发送错误警告，跳出函数
            return this.$message.error('请补全商品信息');
          }else {
            // 对addForm数据进行深拷贝
            let addData = _.cloneDeep(this.addForm);
            addData.attrs = []
            // 处理分类数据 将数组转换为字符串
            addData.goods_cat = addData.goods_cat.join(',');
            // 处理动态参数 
            addData.many_attrs.forEach( item => {
              let obj = {
                attr_id: item.attr_id,
                attr_value: item.attr_vals.join(' ')
              }
              addData.attrs.push(obj);
              delete addData.many_attrs;
            })
            // 处理静态属性
            addData.only_attrs.forEach( item => {
              let obj = {
                attr_id: item.attr_id,
                attr_value: item.attr_vals
              }
              addData.attrs.push(obj);
              delete addData.only_attrs;
            })
            // 调用添加商品API
            // console.log(addData);
            postAddGood(addData)
              .then(()=>{
                this.$message({ message: '添加成功！', type: 'success' });
                this.$router.push('/goods');
              })
              .catch(() => {this.$message.error('操作失败！')})
          }
        })
        
      }
    },
    components: {
      breadCrumb,
    }
  }
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
/* 利用穿透，设置input边框隐藏 */
.inputDeep /deep/ .el-input__inner {
  border: 0;
}
.inputDeep {
  border-bottom: 2px solid #d5d4d4;
  width: 80%;
}
// 图片预览样式
.previewImg {
  max-width: 100%;
  max-height: 60vh;
}
// 添加商品按钮样式
.addButton {
  margin-top: 15px;
}
</style>